import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { RepoService } from '@/service/repo.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { GiteeRepo } from '@/models/GiteeRepo';

@Component({
  selector: 'app-issues-add',
  templateUrl: './issues-add.component.html',
  styleUrls: ['./issues-add.component.less']
})
export class IssuesAddComponent implements OnInit {

  validateForm!: FormGroup;
  urlParamRepos!: GiteeRepo;

  constructor(private location: Location, private fb: FormBuilder, private repoService: RepoService, private message: NzMessageService, private activatedRoute: ActivatedRoute) { }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe((param) => {
      this.urlParamRepos = param

      console.log(this.urlParamRepos)
    });

    let group = {
      kind: ['Enterprises', [Validators.required]],
      repo: [null, []],
      program: ['P1007', []],
      title: [null, [Validators.minLength(4), Validators.required]],
      body: [null, [Validators.minLength(10), Validators.required]],
    }

    if (this.urlParamRepos.owner) {
      group = Object.assign({},
        group,
        {
          kind: ['Repo', [Validators.required]],
          program: [null, []],
          repo: [`${this.urlParamRepos.owner}/${this.urlParamRepos.repo}`, []]
        })
    }
    this.validateForm = this.fb.group(group);
  }

  goback() {
    this.location.historyGo(-1);
  }



  submitForm(): void {
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
      this.repoService.createIssue(this.validateForm.value).subscribe(el => {
        if (el) {
          this.message.create('success', `新增成功`);
          this.goback();
        } else {
          this.message.create('error', `新增失败`);
        }
      })

    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    // Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    // if (!control.value) {
    //   return { required: true };
    // } else if (control.value !== this.validateForm.controls.password.value) {
    //   return { confirm: true, error: true };
    // }
    return {};
  };

}
